<template>
  <div class="userInfo">
    <a-card title="个人信息">
      <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="昵称">
          <a-input v-model:value="formState.userName" />
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea v-model:value="formState.userProfile" :rows="4" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="formState.userPhone" />
        </a-form-item>
        <a-form-item label="头像">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%" />
            <div v-else>
              <loading-outlined v-if="loading" />
              <plus-outlined v-else />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="密码">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

interface FormState {
  userName: string;
  userProfile: string;
  userPhone: string;
  password: string;
  avatar: File | null;
}

const formState = reactive<FormState>({
  userName: '',
  userProfile: '',
  userPhone: '',
  password: '',
  avatar: null,
});

const labelCol = { span: 4 };
const wrapperCol = { span: 14 };

const imageUrl = ref<string>('');
const loading = ref<boolean>(false);

const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG or PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const handleChange = (info: any) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    imageUrl.value = info.file.response.url; // 假设后端返回的 URL 在 response.url 中
    formState.avatar = info.file.originFileObj;
    loading.value = false;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('Upload failed.');
  }
};

const onSubmit = async () => {
  try {
    const formData = new FormData();
    formData.append('userName', formState.userName);
    formData.append('userProfile', formState.userProfile);
    formData.append('userPhone', formState.userPhone);
    formData.append('password', formState.password);
    if (formState.avatar) {
      formData.append('avatar', formState.avatar);
    }

    const response = await axios.post('/api/user/edit', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    if (response.data.code === 0) {
      message.success('个人信息更新成功');
    } else {
      message.error('个人信息更新失败: ' + response.data.message);
    }
  } catch (error) {
    console.error('更新个人信息时出错:', error);
    message.error('更新个人信息时出错');
  }
};

// 假设有一个获取用户信息的 API
const fetchUserInfo = async () => {
  try {
    const response = await axios.get('/api/user/info');
    if (response.data.code === 0) {
      const userInfo = response.data.data;
      formState.userName = userInfo.userName;
      formState.userProfile = userInfo.userProfile;
      formState.userPhone = userInfo.userPhone;
      imageUrl.value = userInfo.avatar;
    } else {
      message.error('获取用户信息失败: ' + response.data.message);
    }
  } catch (error) {
    console.error('获取用户信息时出错:', error);
    message.error('获取用户信息时出错');
  }
};

fetchUserInfo();
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
